package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DevicePackageCoverPicture;
import com.inter.entity.common.PartnerProductPackage;
import com.inter.entity.interentity.home.request.RequestPackageHome;
import com.inter.entity.interentity.home.request.RequestPackageHomeData;
import com.inter.entity.interentity.home.response.ResponsePackageHome;
import com.inter.entity.interentity.home.response.ResponsePackageHomeCoverCountry;
import com.inter.entity.interentity.home.response.ResponsePackageHomeData;
import com.inter.entity.interentity.home.response.ResponsePackageHomeTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前端商城获取设备套餐信息的类，首页
 *
 * @author lm
 * @date 2018/8/30
 */
@RestController
@Api(description = "首页套餐")
public class HomePageController {

    private static Logger logger = Logger.getLogger(HomePageController.class);

    @Autowired
    SequenceService sequenceService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;
    @Autowired
    PartnerService partnerService;

    @CrossOrigin
    @RequestMapping(value = "homepage", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "首页", response = ResponsePackageHome.class)
    public String homePage(@ApiParam @RequestBody RequestPackageHome requestPackageHome) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        String requestStr = JSON.toJSONString(requestPackageHome);
        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestPackageHome requestPackage = JSONArray.parseObject(requestStr, RequestPackageHome.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestPackageHomeData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String TOKEN = partnerService.findTokenByPartnerCode(partnerCode);
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    //lang为空或者为null时，默认为cn
                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType)) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        logger.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            logger.info("签名验证失败！");
                            jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                            return jsonString;
                        } else {
                            //签名验证通过,代码在此处添加,下面都是为了准备response的参数

                            String packageType = null;
                            String packageCode = null;
                            String pachageName = null;
                            String pachageNameEN = null;
                            String packageDesc = null;
                            String appScope = null;
                            String priceType = null;
                            String packageFlow = null;
                            String buyType = null;
                            String minOrderPeriod = null;
                            String maxOrderPeriod = null;
                            String coverCountryMcc = null;
                            String coverCountrys = null;
                            String coverCountrysEN = null;
                            String continentName = null;
                            String continentNameEN = null;
                            String pictureIndex = null;

                            List<ResponsePackageHomeTradeData> tradeData = new ArrayList<ResponsePackageHomeTradeData>();
                            ResponsePackageHomeTradeData tra = null;

                            List<PartnerProductPackage> partnerProductPackageList = partnerProductPackageService.getProductListByPartnerCode(partnerCode);

                            if (partnerProductPackageList == null || partnerProductPackageList.size() <= 0) {
                                //如果没有取到相应的值，也要个前端回复一个公众的报文
                                logger.info("当前渠道无上线套餐！");
                                jsonString = utils.requestCannotRespondMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {

                                for (PartnerProductPackage product : partnerProductPackageList) {

                                    packageType = product.getPackageType();
                                    packageCode = product.getPackageCode();
                                    pachageName = product.getPackageName();
                                    pachageNameEN = product.getPackageNameEN();
                                    packageDesc = product.getPackageDesc();
                                    appScope = product.getAppScope();
                                    priceType = product.getPriceType();
                                    packageFlow = product.getPackageFlow();
                                    buyType = product.getBuyType();
                                    minOrderPeriod = product.getMinOrderPeriod();
                                    maxOrderPeriod = product.getMaxOrderPeriod();
                                    coverCountryMcc = product.getCoverCountryMcc();
                                    coverCountrys = product.getCoverCountrys();
                                    coverCountrysEN = product.getCoverCountrysEN();
                                    continentName = product.getContinentName();
                                    continentNameEN = product.getContinentNameEN();

                                    // 1,从CoverPicture表中把图片信息取出来 ,packageCode,partnerCode
                                    List<DevicePackageCoverPicture> pictureList = partnerProductPackageService.getPictureByPartnerCodeAndPackageCode(packageCode, partnerCode);

                                    for (DevicePackageCoverPicture covers : pictureList) {
                                        pictureIndex = covers.getPictureIndex();
                                    }

                                    // 2,从PackageMarketingStrategy表中把营销信息取出来 ,partnerCode

                                    //1,给coverCountry赋值：
                                    List<ResponsePackageHomeCoverCountry> coverCountryList = new ArrayList();
                                    ResponsePackageHomeCoverCountry cover = new ResponsePackageHomeCoverCountry();
                                    cover.setMcc(coverCountryMcc);
                                    //将原来展示国家的位置现在改成文字描述（首页）比如，新马泰 ,现在就他展示国家名称
                                    if ("en".equals(lang)) {
                                        cover.setCountryName(coverCountrysEN);
                                    } else {
                                        cover.setCountryName(coverCountrys);
                                    }
                                    //为了解决39个国家continentName大洲名字就有39个欧洲，就显示一个欧洲
                                    if (continentName != null && !"".equals(continentName) && ("cn".equals(lang) || StringUtils.isBlank(lang))) {

                                        String continent = continentName.split(",")[0];

                                        cover.setContinentName(continent);

                                    } else if (continentNameEN != null && !"".equals(continentNameEN) && ("en".equals(lang))) {
                                        String continentEN = continentNameEN.split(",")[0];
                                        cover.setContinentName(continentEN);
                                    }
                                    coverCountryList.add(cover);
                                    //2,给tradeData赋值
                                    tra = new ResponsePackageHomeTradeData();
                                    tra.setPackageType(packageType);
                                    tra.setPackageCode(packageCode);
                                    if ("en".equals(lang)) {
                                        tra.setPackageName(pachageNameEN);
                                    } else {
                                        tra.setPackageName(pachageName);
                                    }
                                    //同步套餐的时候packageDesc给我传了空的字符串，这边判断一下，是空的就不要传
                                    if (StringUtils.isNotBlank(packageDesc)) {
                                        tra.setPackageDesc(packageDesc);
                                    } else {
                                        tra.setPackageDesc("");
                                    }
                                    tra.setAppScope(appScope);
                                    tra.setPriceType(priceType);
                                    tra.setPackageFlow(packageFlow);
                                    tra.setBuyType(buyType);
                                    tra.setMinOrderPeriod(minOrderPeriod);
                                    tra.setMaxOrderPeriod(maxOrderPeriod);
                                    //价格
                                    tra.setPictureIndex(pictureIndex);
                                    tra.setCoverCountry(coverCountryList);
                                    tradeData.add(tra);
                                }

                                //循环结束，开始赋值data
                                ResponsePackageHomeData data = new ResponsePackageHomeData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeTime(curtime);
                                data.setTradeType(tradeType);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(tradeData);
                                //赋值ResponsePackageHome
                                ResponsePackageHome home = new ResponsePackageHome();
                                home.setData(data);
                                home.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                                // 返回给调用者的报文
                                jsonString = JSON.toJSONString(home);
                                //logger.info("响应报文：" + jsonString);
                                return jsonString;
                            }
                        }
                    }
                }
            }
        }
    }
}